package cn.jdx.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloController {

    @RequestMapping({"/","/index","index.html"})
    public String toIndex(Model model){
        model.addAttribute("msg","Hello Shiro!");
        return "index";
    }
    @RequestMapping("/user/update")
    public String update(Model model){
        System.out.println("update");
        model.addAttribute("msg","Hello Shiro!");
        return "user/update";
    }

    @RequestMapping("/user/add")
    public String add(Model model){
        System.out.println("add");
        model.addAttribute("msg","Hello Shiro!");
        return "user/add";
    }

    @RequestMapping("/toLogin")
    public String toLogin(Model model) {
        System.out.println("toLogin");
        return "login";
    }

    //用户登录
    @RequestMapping("/login")
    public String login(String username, String password, Model model) {
        System.out.println("login");
        //(1)获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //(2)封装用户的登录数据(使用用户名密码加密并且得到令牌)
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        //(3)处理
        try {
            subject.login(token);//执行登录方法(如果没有异常就登录成功)
            System.out.println("登录成功");
            return "index";
        } catch (UnknownAccountException uae) {
            model.addAttribute("msg", "账号不存咋!");
            System.out.println("密码错误");
            return "login";
        } catch (IncorrectCredentialsException ice) {
            model.addAttribute("msg", "密码错误!");
            System.out.println("密码错误");
            return "login";
        } catch (LockedAccountException lae) {
            model.addAttribute("msg", "用户被锁定!");
            return "login";
        } catch (AuthenticationException ae) {
            model.addAttribute("msg", "身份验证异常!");
        }
        return "login";
    }

}
